package com.neuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * @author myh
 * @version 2019年8月15日下午1:53:50
 *
 */
public class ChatServer {

	public static void main(String[] args) {
		// 设置服务器监听端口，启动服务器监听

		int port = 8888;
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			//1.启动服务器监听
			serverSocket = new ServerSocket(port);
			System.out.println("服务器启动成功，请使用客户端进行连接，再见~");
			//2.等待客户端进行连接
			socket = serverSocket.accept();
			System.out.println("欢迎来到天堂！");
			//3.客户端连接后，打开输入流（准备从客户端读取数据输入）
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			//4.读取客户端发送过来的数据
			byte[] buffer = new byte[512];
			//等待客户端发送数据，并接收 - 有阻塞作用
			int len = inputStream.read(buffer);
			//5.对数据进行处理
			String str = new String(buffer, 0, len);
			System.out.println(str);
			outputStream.write(("see me "+str).getBytes("GBK"));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//6.关闭输入流
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
				}
			}
		}
	}
}
